using System.Collections;
using System.IO;
using SCore.Util;

namespace Function.HotUpdate
{
    public class HotSaveVersion : HotStep
    {
        public override HotState GetHotState()
        {
            return HotState.SaveVersion;
        }

        public HotSaveVersion(HotContext hotContext, bool cb) : base(hotContext, cb)
        {
        }

        protected override IEnumerator OnExecute()
        {
            if (!_hotContext._needUpdate)
            {
                SetSuccess(true);
                _hotContext._version = _hotContext._remoteVersion;
                yield return Finish();
                yield break;
            }

            var cachePath = UnityUtils.GetCacheDirectory();
            if (!Directory.Exists(cachePath))
            {
                Directory.CreateDirectory(cachePath);
            }

            string path = cachePath + '/' + _hotContext._assetsVersion;
            File.WriteAllText(path, _hotContext._remoteVersion.ToString());
            _hotContext._version = _hotContext._remoteVersion;
            SetSuccess(true);
            $"[HotUpdate] _firstHotFinish{HotContext._firstHotFinish} _updateDll {_hotContext._updateDll}".Log();
            if (HotContext._firstHotFinish && _hotContext._updateDll)
            {
                _hotContext.Error("HotManager", "热更新dll需要重启", (int)HotUpdateErrorType.NeedStopGame);
                SetSuccess(false);
                yield break;
            }

            bool initAddressableResult = false;
            yield return HotManager.InitAddressableWithTimeout(15f, b => { initAddressableResult = b; });
            if (!initAddressableResult)
            {
                SetSuccess(false);
                yield break;
            }

            yield return Finish();
        }
    }
}